package com.edgclub.edg.utils.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.rockerhieu.emojicon.emoji.CommDiledata;
import com.rockerhieu.emojicon.emoji.SerializeManager;

import org.apache.http.util.EncodingUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("SimpleDateFormat")
public class StringUtils {
	public static void postToast(Context context, String s) {
		View toastRoot=null;
		Toast toast=new Toast(GuZhiApplication.getInstance().getApplicationContext());
		 toastRoot = ((Activity) context).getLayoutInflater().inflate(R.layout.layout_gz_toast, null);
		 TextView tv=(TextView)toastRoot.findViewById(R.id.toast_text);
		 tv.setText(""+s);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.setGravity(Gravity.CENTER, 0, 0);

		toast.show();
	}
	public static void postToast2(Context context, String s, String s1) {
		View toastRoot=null;
		Toast toast=new Toast(GuZhiApplication.getInstance().getApplicationContext());
		 toastRoot = ((Activity) context).getLayoutInflater().inflate(R.layout.layout_gz_toast2, null);
		 TextView tv=(TextView)toastRoot.findViewById(R.id.content_text);
		 TextView tv1=(TextView)toastRoot.findViewById(R.id.value);
		 tv.setText("任务完成："+s);
		 tv1.setText("+"+s1);
		toast.setDuration(5000);
		toast.setView(toastRoot);
		toast.setGravity(Gravity.CENTER, 0, 0);

		toast.show();
	}
	//获取版本号
	public static String getVersion(Context context)  {
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
	private final static Pattern emailer = Pattern
			.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

	private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {

		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};
	public static int getChatCount(String str){
		int count = 0;
		String regEx = "[\\u4e00-\\u9fa5]";
		//System.out.println(regEx);
		//System.out.println(str);
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		while (m.find()) {
			for (int i = 0; i <= m.groupCount(); i++) {
				count = count + 1;
			}
		}
		return count;
	}
	/**
	 * 判断手机号
	 */
	public static boolean isPhoneNum(String str) {
//		String s = "^1(3[0-9]|4[7]|5[^4]|8[0-9]|7[078]|44)\\d{8}";
		String s = "^1(3[0-9]|4[7]|5[^4]|8[0-9]|7[01768]|44)\\\\d{8}$";

		CommDiledata commDiledata= (CommDiledata) SerializeManager.loadFile(SerializeManager.regularString);
		if(null!=commDiledata&&!"".equals(commDiledata.getRegexp())){
			s=commDiledata.getPhone();
		}
		Pattern p = Pattern.compile(s);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	public static boolean isMatchPsw(String psw) {
		// String s = "^\\w{8,24}$";
		String s = "^([。~!@#$%^+*&/?|:.<>{}()';=]+|[a-zA-Z0-9]){8,24}$";
		Pattern p = Pattern.compile(s);
		Matcher m = p.matcher(psw);
		return m.matches();
	}

	/**
	 * 将字符串转位日期类型
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		try {
			return dateFormater.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 以友好的方式显示时间
	 * 
	 * @param sdate
	 * @return
	 */
	public static String friendly_time(String sdate, Long milliseconds,
			Date date) {
		Date time = null;
		if (sdate != null) {
			time = toDate(sdate);
		}
		if (milliseconds != null) {
			time = new Date(milliseconds);
		}
		if (date != null) {
			time = date;
		}
		if (time == null) {
			return "Unknown";
		}
		String ftime = "";
		Calendar cal = Calendar.getInstance();

		// 判断是否是同一天
		String curDate = dateFormater2.get().format(cal.getTime());
		String paramDate = dateFormater2.get().format(time);
		if (curDate.equals(paramDate)) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max(
						(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
						+ "分钟前";
			else
				ftime = hour + "小时前";
			return ftime;
		}

		long lt = time.getTime() / 86400000;
		long ct = cal.getTimeInMillis() / 86400000;
		int days = (int) (ct - lt);
		if (days == 0) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max(
						(cal.getTimeInMillis() - time.getTime()) / 60000, 1)
						+ "分钟前";
			else
				ftime = hour + "小时前";
		} else if (days == 1) {
			ftime = "昨天";
		} else if (days == 2) {
			ftime = "前天";
		} else if (days > 2 && days <= 10) {
			ftime = days + "天前";
		} else if (days > 10) {
			ftime = dateFormater2.get().format(time);
		}
		return ftime;
	}

	/**
	 * 判断给定字符串时间是否为今日
	 * 
	 * @param sdate
	 * @return boolean
	 */
	public static boolean isToday(String sdate) {
		boolean b = false;
		Date time = toDate(sdate);
		Date today = new Date();
		if (time != null) {
			String nowDate = dateFormater2.get().format(today);
			String timeDate = dateFormater2.get().format(time);
			if (nowDate.equals(timeDate)) {
				b = true;
			}
		}
		return b;
	}

	/**
	 * 判断是不是一个合法的电子邮件地址
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		if (email == null || email.trim().length() == 0)
			return false;
		return emailer.matcher(email).matches();
	}

	/**
	 * 字符串转整数
	 * 
	 * @param str
	 * @param defValue
	 * @return
	 */
	public static int toInt(String str, int defValue) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
		}
		return defValue;
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static int toInt(Object obj) {
		if (obj == null)
			return 0;
		return toInt(obj.toString(), 0);
	}

	/**
	 * 对象转整数
	 * 
	 * @param obj
	 * @return 转换异常返回 0
	 */
	public static long toLong(String obj) {
		try {
			return Long.parseLong(obj);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * 字符串转布尔值
	 * 
	 * @param b
	 * @return 转换异常返回 false
	 */
	public static boolean toBool(String b) {
		try {
			return Boolean.parseBoolean(b);
		} catch (Exception e) {
		}
		return false;
	}

	// // 判断字符串用那个前缀
	// public static String Judge(String str) {
	// if (str == null) {
	// return "";
	// }
	// // 判断是否有/data
	// String regHx = "/data";
	// Pattern path = Pattern.compile(regHx);
	// Matcher math = path.matcher(str);
	// boolean ish = math.find();
	// // 判断是否有/http://
	// String regHy = "http://";
	// Pattern paty = Pattern.compile(regHy);
	// Matcher maty = paty.matcher(str);
	// boolean isy = maty.find();
	// // 判断是否有/public
	// String regHp = "/public";
	// Pattern patp = Pattern.compile(regHp);
	// Matcher matp = patp.matcher(str);
	// boolean isp = matp.find();
	//
	// if (ish) {
	// return AppConstant.Url.ROOTSNS + str;
	// } else if (isy) {
	// return str;
	// } else if (isp) {
	// return AppConstant.Url.ROOTSNS + str;
	// } else {
	// return AppConstant.Url.ROOTSNS + str;
	// }
	// }

	/**
	 * 返回字符串中间省略后串 例如 111111111111111@qq.com 返回 111...111@qq.com
	 * 
	 * @param str
	 *            待处理字符串
	 * @param maxLength
	 *            允许最长长度
	 * @return
	 */
	public static String EllipsisMiddle(String str, int maxLength) {
		if (TextUtils.isEmpty(str) || str.length() <= maxLength) {
			return str;
		}
		return str.substring(0, maxLength / 2) + "..."
				+ str.substring(str.length() - maxLength / 2, str.length());

	}

	/**
	 * 返回字符串中最后省略后串 例如 “哈哈哈哈哈哈哈哈哈哈” 返回 哈哈哈哈...
	 * 
	 * @param str
	 *            待处理字符串
	 * @param maxLength
	 *            允许最长长度
	 * @return
	 */
	public static String EllipsisEnd(String str, int maxLength) {
		if (TextUtils.isEmpty(str) || str.length() <= maxLength) {
			return str;
		}
		return str.substring(0, maxLength) + "...";

	}

	/**
	 * @description 获取一段字符串的字符个数（包含中英文，一个中文算2个字符）
	 * @param content
	 * @return
	 */
	public static int getCharacterNum(final String content) {
		if (null == content || "".equals(content)) {
			return 0;
		} else {
			return (content.length() + getChineseNum(content));
		}
	}

	/**
	 * @description 返回字符串里中文字或者全角字符的个数
	 * @param s
	 * @return
	 */
	public static int getChineseNum(String s) {
		int num = 0;
		char[] myChar = s.toCharArray();
		for (int i = 0; i < myChar.length; i++) {
			if ((char) (byte) myChar[i] != myChar[i]) {
				num++;
			}
		}
		return num;
	}

	public static String ToSBC(String input) {
		// 半角转全角：
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	// 把img替换成可以点击打开
	public static String ReplaceImgTag(String html) {

		if (html == null)
			return "";
		Pattern patternImgSrc1 = Pattern.compile("<img(.+?)src=(.+?) ");
		Matcher m = patternImgSrc1.matcher(html);
		// if (AppConstant.IsLowMemory) {
		// while (m.find()) {
		// html =
		// m.replaceAll("<img id=$2 style='width:100%;margin-top:5px;'  src='file:///android_res/drawable/empty_photo.png'  ");
		// }
		// }

		// else {
		while (m.find()) {
			html = m.replaceAll("<img id=$2 style='width:100%;margin-top:5px;' onclick=\"javascript:window.androidWebView.openBigPicture($2);\" src='file:///android_res/drawable/empty_photo.png'  ");
		}
		// }

		return html;
	}

	/**
	 * 将InputStream转换成String
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static String InputStreamTOString(InputStream in) throws Exception {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int count = -1;
		while ((count = in.read(data, 0, 1024)) != -1)
			outStream.write(data, 0, count);

		data = null;
		return new String(outStream.toByteArray(), "utf-8");
	}

	/**
	 * 星座
	 * 
	 * @param type
	 * @return
	 */
	public static String getStarStr(int type) {
		String s = "";

		switch (type) {
		case 1:
			s = getString(R.string.start1);
			break;

		case 2:
			s = getString(R.string.start2);
			break;
		case 3:
			s = getString(R.string.start3);
			break;
		case 4:
			s = getString(R.string.start4);
			break;
		case 5:
			s = getString(R.string.start5);
			break;
		case 6:
			s = getString(R.string.start6);
			break;
		case 7:
			s = getString(R.string.start7);
			break;
		case 8:
			s = getString(R.string.start8);
			break;
		case 9:
			s = getString(R.string.start9);
			break;
		case 10:
			s = getString(R.string.start10);
			break;
		case 11:
			s = getString(R.string.start11);
			break;
		case 12:
			s = getString(R.string.start12);
			break;

		}

		return s;
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	// 从assets 文件夹中获取文件并读取数据
	public static String getFromAssets(Context contenxt, String fileName) {
		String result = "";
		InputStream in = null;
		AssetManager assetManager = null;
		try {
			assetManager = contenxt.getResources().getAssets();
			in = assetManager.open(fileName);
			// 获取文件的字节数
			int lenght = in.available();
			// 创建byte数组
			byte[] buffer = new byte[lenght];
			// 将文件中的数据读到byte数组中
			in.read(buffer);
			result = EncodingUtils.getString(buffer, "utf-8");
			if (null != in) {
				in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String getString(int id){
		Context context = GuZhiApplication.getInstance();
		return context.getResources().getString(id);
	}
}
